/* 自定义元素类 */
class CustomButton extends HTMLElement {
    static template = `
    <button>自定义按钮</button>
    <style>
        button {
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            text-align: center;
            box-sizing: border-box;
            outline: none;
            margin: 0;
            transition: .1s;
            font-weight: 500;
            padding: 12px 20px;
            font-size: 14px;
            border-radius: 4px;
            color: #fff;
            background-color: #409eff;
            border-color: #409eff;
            border: 0;
        }

        button:active {
            background: #3a8ee6;
            border-color: #3a8ee6;
            color: #fff;
        }
    </style>
    `;

    static templateInited = false;
    static initTemplate() {
        if (!this.templateInited) {
            const tp = document.createElement("template");
            tp.id = "custom-button";
            tp.innerHTML = this.template;
            // document.body.insertBefore(tp, document.body.childNodes[0]);
            document.querySelector("#tps").appendChild(tp);
            this.templateInited = true;
        }
    }

    constructor() {
        // 必须首先调用 super方法
        super();

        // 将自定义组件的模板放入页面中
        CustomButton.initTemplate();

        // 页面打开时创建一个影子DOM
        const shadowRoot = this.attachShadow({ mode: "open" });
        this.render(shadowRoot);
        this.initListeners();
    }

    // 事件监听器
    initListeners() {
        this.btn.onclick = () => {
            alert("Hello World!");
        };
    }

    // 往影子根元素中渲染DOM
    render(shadowRoot) {
        shadowRoot.appendChild(
            document.getElementById("custom-button").content.cloneNode(true)
        );
        this.btn = shadowRoot.querySelector("button");
    }

    /* 生命周期（非必须） */
    connectedCallback() {
        console.log("connected");
    }
}

/* 创建自定义元素 */
customElements.define("custom-button", CustomButton);
